import asyncio
import time
from loguru import logger
from typing import Dict, Any


class DelayedGuideScheduler:
    """延迟引导话术调度器"""
    
    def __init__(self):
        self.running = False
        self.check_interval = 10  # 每10秒检查一次
        self.xianyu_instances = {}  # 存储XianyuLive实例 {cookie_id: xianyu_instance}
        
    def register_xianyu_instance(self, cookie_id: str, xianyu_instance):
        """注册XianyuLive实例"""
        self.xianyu_instances[cookie_id] = xianyu_instance
        logger.debug(f"注册XianyuLive实例: {cookie_id}")
        
    def unregister_xianyu_instance(self, cookie_id: str):
        """注销XianyuLive实例"""
        if cookie_id in self.xianyu_instances:
            del self.xianyu_instances[cookie_id]
            logger.debug(f"注销XianyuLive实例: {cookie_id}")
    
    async def start(self):
        """启动调度器"""
        if self.running:
            logger.warning("延迟引导调度器已在运行")
            return
            
        self.running = True
        logger.info("启动延迟引导话术调度器")
        
        # 记录上次清理时间
        last_cleanup_time = 0
        cleanup_interval = 3600  # 1小时清理一次
        
        while self.running:
            try:
                await self._process_pending_tasks()
                
                # 定期清理旧记录
                current_time = asyncio.get_event_loop().time()
                if current_time - last_cleanup_time > cleanup_interval:
                    await self._cleanup_old_records()
                    last_cleanup_time = current_time
                
                await asyncio.sleep(self.check_interval)
            except Exception as e:
                logger.error(f"延迟引导调度器处理异常: {e}")
                await asyncio.sleep(self.check_interval)
    
    async def stop(self):
        """停止调度器"""
        self.running = False
        logger.info("停止延迟引导话术调度器")
    
    async def _process_pending_tasks(self):
        """处理待发送的延迟引导任务"""
        try:
            from db_manager import db_manager
            
            # 获取所有待发送的任务
            pending_tasks = db_manager.get_pending_delayed_guide_tasks()
            
            if not pending_tasks:
                return
                
            logger.debug(f"发现 {len(pending_tasks)} 个待发送的延迟引导任务")
            
            for task in pending_tasks:
                await self._process_single_task(task)
                
        except Exception as e:
            logger.error(f"处理延迟引导任务失败: {e}")
    
    async def _process_single_task(self, task: Dict[str, Any]):
        """处理单个延迟引导任务"""
        try:
            from db_manager import db_manager
            
            task_id = task['id']
            cookie_id = task['cookie_id']
            user_id = task['user_id']
            chat_id = task['chat_id']
            item_id = task.get('item_id')
            
            logger.info(f"处理延迟引导任务: {task_id}, 账号: {cookie_id}, 用户: {user_id}")
            
            # 检查是否需要跳过该任务（用户已发送新消息或已下单）
            if await self._should_skip_task(cookie_id, user_id, chat_id, task['trigger_time']):
                # 取消任务
                db_manager.cancel_delayed_guide_tasks(cookie_id, user_id, chat_id)
                logger.info(f"跳过延迟引导任务 {task_id}: 用户已发送新消息或已下单")
                return
            
            # 发送引导话术
            success = await self._send_guide_message(cookie_id, user_id, chat_id, item_id)
            
            if success:
                # 标记任务为已发送
                db_manager.mark_delayed_guide_task_sent(task_id)
                logger.info(f"延迟引导任务 {task_id} 发送成功")
            else:
                logger.warning(f"延迟引导任务 {task_id} 发送失败")
                
        except Exception as e:
            logger.error(f"处理延迟引导任务异常: {e}")
    
    async def _should_skip_task(self, cookie_id: str, user_id: str, chat_id: str, trigger_time: str) -> bool:
        """检查是否应该跳过该任务"""
        try:
            # 这里需要检查以下情况：
            # 1. 用户在触发时间后是否发送了新消息
            # 2. 用户是否已经下单（检测到下单相关消息）
            
            # 由于消息历史记录的实现比较复杂，这里先返回False
            # 实际使用中可以根据需要实现具体的检查逻辑
            # 比如检查数据库中的消息记录或订单状态
            
            return False
            
        except Exception as e:
            logger.error(f"检查任务跳过条件异常: {e}")
            return False
    
    async def _send_guide_message(self, cookie_id: str, user_id: str, chat_id: str, item_id: str = None) -> bool:
        """发送引导话术消息"""
        try:
            from db_manager import db_manager
            
            # 获取引导话术内容
            guide_text = db_manager.get_system_setting('delayed_guide_text')
            if not guide_text:
                guide_text = "亲，库存有限，如果有您要去的门店，请尽快下单哦"
            
            # 获取对应的XianyuLive实例
            xianyu_instance = self.xianyu_instances.get(cookie_id)
            if not xianyu_instance:
                logger.warning(f"未找到账号 {cookie_id} 的XianyuLive实例，无法发送引导话术")
                return False
            
            # 检查websocket连接是否可用
            if not hasattr(xianyu_instance, 'ws') or xianyu_instance.ws is None:
                logger.warning(f"账号 {cookie_id} 的websocket连接不可用，无法发送引导话术")
                return False
            
            # 使用XianyuLive实例的send_msg方法发送消息
            await xianyu_instance.send_msg(xianyu_instance.ws, chat_id, user_id, guide_text)
            
            logger.info(f"延迟引导话术发送成功: 账号={cookie_id}, 用户={user_id}, 内容={guide_text}")
            return True
            
        except Exception as e:
            logger.error(f"发送引导话术异常: {e}")
            return False
    
    async def _cleanup_old_records(self):
        """清理旧的延迟引导任务记录"""
        try:
            from db_manager import db_manager
            success = db_manager.cleanup_old_delayed_guide_tasks(days_old=7)
            if success:
                logger.info("旧的延迟引导任务记录清理完成")
        except Exception as e:
            logger.error(f"清理旧记录失败: {e}")


# 全局调度器实例
delayed_guide_scheduler = DelayedGuideScheduler() 